﻿using famails.App_Code.source.bus;
using famails.App_Code.source.dto;
using famails.bus;
using famails.dto;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace famails.BackEnd.Customer
{
    public partial class Orders : System.Web.UI.Page
    {
        static log4net.ILog logs = log4net.LogManager.GetLogger("ErrorRollingLogFileAppender");
        static UserLoginDTO userLogin = null;
        CM_OrderBUS bus = new CM_OrderBUS();
        public string OrderDate, DeliveryDate;
        protected void Page_Load(object sender, EventArgs e)
        {
            userLogin = getUserLogin();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static CM_OrderDTO Load4Edit(decimal id)
        {
            CM_OrderDTO dto = new CM_OrderDTO();
            if (id > 0)
            {
                CM_OrderBUS bus = new CM_OrderBUS();
                DataTable source = bus.GetByID(id, userLogin.UserId);
                if (source != null && source.Rows.Count > 0)
                {
                    dto.OrderID = Convert.ToDecimal(source.Rows[0]["orderID"]);
                    dto.DeliveryFee = Convert.ToDecimal(source.Rows[0]["DeliveryFee"]);
                    dto.DeliveryDate = Convert.ToDateTime(source.Rows[0]["DeliveryDate"]);
                    dto.Deposit = Convert.ToDecimal(source.Rows[0]["Deposit"]);
                    dto.OrderDate = Convert.ToDateTime(source.Rows[0]["OrderDate"]);
                    dto.CustomerID = Convert.ToDecimal(source.Rows[0]["CustomerID"]);
                    dto.Delivery = source.Rows[0]["Delivery"] + "";
                    dto.Payment = source.Rows[0]["Payment"] + "";
                    dto.Status = source.Rows[0]["Status"] + "";
                    dto.OrderCode = source.Rows[0]["OrderCode"] + "";
                    dto.DeliveryCode = source.Rows[0]["DeliveryCode"] + "";
                    dto.Note = source.Rows[0]["Note"] + "";
                    dto.DiscountAmount = Convert.ToDecimal(source.Rows[0]["DiscountAmount"]);
                    
                    dto.Fix0_Per1 = Convert.ToInt32(source.Rows[0]["Fix0_Per1"]);
                    dto.MinAmount = Convert.ToDecimal(source.Rows[0]["MinAmount"]);
                    dto.DiscountValue = Convert.ToDecimal(source.Rows[0]["DiscountValue"]);
                    dto.DiscountCode = source.Rows[0]["DiscountCode"] + "";

                    dto.Reciever = Convert.ToBoolean(source.Rows[0]["Reciever"]);
                    dto.RecieverName = source.Rows[0]["RecieverName"] + "";
                    dto.RecieverPhone = source.Rows[0]["RecieverPhone"] + "";
                    dto.RecieverAddress = source.Rows[0]["RecieverAddress"] + "";

                    DataTable details = bus.GetDetail(dto.OrderID);
                    dto.Items = new List<CM_OrderDetailDTO>();
                    CM_OrderDetailDTO detail = null;
                    foreach (DataRow row in details.Rows)
                    {
                        detail = new CM_OrderDetailDTO();
                        detail.OrderID = Convert.ToDecimal(row["OrderID"]);
                        detail.ProductID = Convert.ToDecimal(row["ProductID"]);
                        detail.ProductCode = row["ProductCode"] + "";
                        detail.ProductName = row["ProductName"] + "";
                        detail.Price = Convert.ToDecimal(row["Price"]);
                        detail.Qty = Convert.ToInt32(row["Qty"]);
                        detail.VAT = Convert.ToDecimal(row["VAT"]);
                        detail.VATAmount = Convert.ToDecimal(row["VATAmount"]);
                        detail.Amount = Convert.ToDecimal(row["Amount"]);
                        dto.Items.Add(detail);
                    }
                }
                if (id != 0 && (source == null || source.Rows.Count == 0))
                {
                    //pnError.Visible = true;
                    //lblError.Text = "Dữ liệu không tồn tại";
                    //return;
                }
            }
            else if (id <= 0)
            {
                //pnError.Visible = true;
                //lblError.Text = "Dữ liệu không tồn tại";
                //return;
            }
            return dto;
        }

        private UserLoginDTO getUserLogin()
        {
            if (Session["us-login"] != null)
            {
                return (UserLoginDTO)Session["us-login"];
            }
            else Response.Redirect("~");
            return null;
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<CM_CustomerDTO> LoadCustomer()
        {
            List<CM_CustomerDTO> result = new List<CM_CustomerDTO>();
            try
            {
                CM_CustomerBUS ulBus = new CM_CustomerBUS();
                DataTable table = ulBus.Search("", "", "", -100, userLogin.UserId, "", "");
                CM_CustomerDTO item = new CM_CustomerDTO();
                foreach (DataRow dr in table.Rows)
                {
                    item = new CM_CustomerDTO();
                    item.CustomerID = Convert.ToInt32(dr["CustomerID"] + "");
                    item.CustomerName = dr["CustomerName"] + "";
                    item.Email = dr["CustomerName"] + "(" + dr["Email"] + ")";
                    result.Add(item);
                }
            }
            catch (Exception ex)
            {
                logs.Error("Order - Search", ex);
            }
            return result;
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static List<CM_ProductGroupDTO> LoadTree()
        {
            List<CM_ProductGroupDTO> result = new List<CM_ProductGroupDTO>();

            CM_ProductGroupBUS bus = new CM_ProductGroupBUS();
            DataTable source = bus.GetProductGroup(userLogin.UserId, 1);
            foreach (DataRow row in source.Rows)
            {
                CM_ProductGroupDTO dto = new CM_ProductGroupDTO();
                dto.ProductGroupName = row["ProductGroupName"] + "";
                dto.ProductGroupID = Convert.ToInt32(row["ProductGroupID"]);
                dto.CreateDate = Convert.ToDateTime(row["CreateDate"]);
                dto.children = GetChildGroup(dto.ProductGroupID, Convert.ToInt32(row["GroupStep"]) + 1);
                result.Add(dto);
            }

            return result;
        }
        static List<CM_ProductGroupDTO> GetChildGroup(int parentid, int groupstep)
        {
            CM_ProductGroupBUS bus = new CM_ProductGroupBUS();
            List<CM_ProductGroupDTO> result = new List<CM_ProductGroupDTO>();
            DataTable source = bus.GetChildGroup(parentid, groupstep, userLogin.UserId);
            foreach (DataRow row in source.Rows)
            {
                CM_ProductGroupDTO dto = new CM_ProductGroupDTO();
                dto.ProductGroupName = row["ProductGroupName"] + "";
                dto.ProductGroupID = Convert.ToInt32(row["ProductGroupID"]);
                dto.children = GetChildGroup(dto.ProductGroupID, Convert.ToInt32(row["GroupStep"]) + 1);
                result.Add(dto);
            }
            return result;
        }

        [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public static List<Product> LoadProduct(int groupid)
        {
            List<Product> result = new List<Product>();
            CM_ProductBUS bus = new CM_ProductBUS();
            DataTable T = bus.Search("", "", groupid, "", "", 0, 0, userLogin.UserId);
            foreach (DataRow r in T.Rows)
            {
                decimal price = 0;
                decimal.TryParse(r["Price"] + "", out price);
                //result.Add(string.Format("{0} - {1} - {2}", r["productCode"], r["productName"], price.ToString("#,##0")));
                Product product = new Product();
                product.html = string.Format("<div tabIndex=0 style='padding: 1px;' id='" + r["ProductCode"] + "'><div>Mã sản phẩm: {0}</div><div>Tên sản phẩm: {1}</div><div>Giá: {2}</div></div>", r["productCode"], r["productName"], price.ToString("#,##0"));
                product.label = r["ProductCode"] + "";
                product.name = r["ProductName"] + "";
                product.price = r["Price"] + "";
                product.id = r["ProductID"] + "";
                result.Add(product);
            }

            return result;
        }
        [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public static CM_ProductDTO GetProduct(string code)
        {
            CM_ProductBUS bus = new CM_ProductBUS();
            DataTable T = bus.GetByCode(code, userLogin.UserId);
            CM_ProductDTO result = new CM_ProductDTO();
            result.ProductName = T.Rows[0]["ProductName"] + "";
            result.ProductCode = T.Rows[0]["ProductCode"] + "";
            result.Price = Convert.ToDecimal(T.Rows[0]["Price"] + "");
            result.ProductID = Convert.ToInt32(T.Rows[0]["ProductID"] + "");
            return result;
        }

        [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public static int CheckExistsOrderCode(string code, decimal orderid)
        {
            CM_OrderBUS bus = new CM_OrderBUS();
            if (bus.CheckExistsOrderCode(code, orderid))
                return 1;
            else return 0;
        }

        [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public static string SaveOrder(string json)
        {
            string result = "";
            try
            {
                CM_OrderBUS bus = new CM_OrderBUS();
                CM_OrderDTO order = Newtonsoft.Json.JsonConvert.DeserializeObject<CM_OrderDTO>(json, new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" });
                if (order.OrderID == 0)
                {
                    order.createBy = userLogin.UserId;
                    order.OrderID = Convert.ToDecimal(bus.Insert(order));
                    if (order.OrderID > 0)
                    {
                        CM_CustomerCareAutoBUS CCABus = new CM_CustomerCareAutoBUS();
                        CCABus.addSendMailFromCustomerCareAutoByCustomer(order.CustomerID, userLogin.UserId);
                        result = "Thêm mới thành công";
                    }
                    else result = "Thêm mới không thành công";
                }
                else if (bus.Edit(order))
                    result = "Cập nhật thành công";
                else result = "Cập nhật không thành công";

                common.Common.logs(userLogin.UserId + "- SaveOrder", null, common.Common.logType.info);
            }
            catch (Exception ex)
            {
                common.Common.logs(userLogin.UserId + "- SaveOrder", ex, common.Common.logType.error);
                throw ex;
            }
            return result;
        }

        [System.Web.Script.Services.ScriptMethod()]
        [System.Web.Services.WebMethod]
        public static CM_DiscountDTO CheckDiscountCode(decimal id, string code, string orderDate)
        {
            try
            {
                CM_DiscountBUS bus = new CM_DiscountBUS();
                DataTable table = bus.GetDiscountValue(id,code, orderDate);
                if (table.Rows.Count > 0)
                {
                    CM_DiscountDTO dto = new CM_DiscountDTO();
                    dto.DiscountValue = Convert.ToInt32(table.Rows[0]["DiscountValue"]);
                    dto.MinAmount = Convert.ToInt32(table.Rows[0]["MinAmount"]);
                    dto.Fix0_Per1 = Convert.ToInt32(table.Rows[0]["Fix0_Per1"]);
                    common.Common.logs(userLogin.UserId + "- CheckDiscountCode - Code:" + code, null, common.Common.logType.info);
                    return dto;
                }
                else throw new Exception("Mã khuyến mãi không hợp lệ!");
            }
            catch (Exception ex)
            {
                common.Common.logs(userLogin.UserId + "- CheckDiscountCode - Code:" + code, ex, common.Common.logType.error);
                throw ex;
            }
        }
    }

    public class Order
    {
        public string OrderCode { get; set; }
        public List<CM_OrderDetailDTO> Items { get; set; }
    }
    public class Product
    {
        public string html { get; set; }
        public string label { get; set; }
        public string id { get; set; }
        public string price { get; set; }
        public string name { get; set; }
    }
}